package org.jash.demo2205.shop

import android.content.Context
import android.view.View
import android.widget.ImageView
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.youth.banner.BannerConfig
import com.youth.banner.loader.ImageLoader
import org.jash.demo2205.BR
import org.jash.demo2205.R
import org.jash.demo2205.databinding.FragmentHomeBinding
import org.jash.demo2205.entity.BannerEntity
import org.jash.demo2205.entity.Goods
import org.jash.demo2205.mvvm.BaseFragment
import org.jash.demo2205.utils.CommonAdapter
import org.jash.demo2205.utils.Event
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import androidx.databinding.DataBindingUtil
import com.google.android.material.search.SearchView
import dagger.hilt.android.AndroidEntryPoint
import org.jash.demo2205.databinding.KeywordBinding
import org.jash.demo2205.entity.Category
import org.jash.demo2205.utils.SPUtils

@AndroidEntryPoint
class HomeFragment : BaseFragment<FragmentHomeBinding, HomeViewModel>() {
    lateinit var adapter: CommonAdapter<Goods>
    lateinit var searchAdapter: CommonAdapter<Goods>
    lateinit var categoryAdapter: CommonAdapter<Category>
    var page = 1
    val size = 10
    var keyword = ""
    override fun initData() {
        adapter = CommonAdapter({ R.layout.item_goods to BR.goods})
        searchAdapter = CommonAdapter({ R.layout.item_goods to BR.goods})
        categoryAdapter = CommonAdapter({R.layout.item_subcategory to BR.sub})
        viewModel.goodsLiveData.observe(viewLifecycleOwner) {
            if (page == 1) {
                adapter.clear()
            }
            adapter += it
            binding.refresh.closeHeaderOrFooter()
        }
        viewModel.bannersLiveData.observe(viewLifecycleOwner) {
            binding.banner.update(it.map(BannerEntity::imagePath), it.map(BannerEntity::desc))
        }
        viewModel.searchLiveData.observe(viewLifecycleOwner) {
            searchAdapter.clear()
            searchAdapter += it
            if (it.isEmpty()) {
                Toast.makeText(requireContext(), "查无数据", Toast.LENGTH_SHORT).show()
            } else {
                SPUtils.instance.putStringSet("keywords", SPUtils.instance.getStringSet("keywords", setOf()) + keyword)
                binding.history.isVisible = false
            }
        }
        viewModel.categoriesLiveData.observe(viewLifecycleOwner) {
            categoryAdapter.clear()
            categoryAdapter += it[0].data ?: listOf()
        }
        viewModel.getCategories()
        viewModel.getBanners()
        page = 1
        viewModel.getGoods(0, page, size)
    }

    override fun initView() {
        binding.recycler.adapter = adapter
        binding.searchRv.adapter = searchAdapter
        binding.category.adapter = categoryAdapter
        binding.banner.setImageLoader(object : ImageLoader() {
            override fun displayImage(context: Context?, path: Any?, imageView: ImageView?) {
                imageView?.let {
                    Glide.with(it)
                        .load(path)
                        .into(it)
                }
            }
        }).setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE)
        binding.refresh.setOnRefreshListener {
            page = 1
            viewModel.getGoods(0, page, size)
        }
        binding.refresh.setOnLoadMoreListener {
            viewModel.getGoods(0, ++page, size)
        }
        binding.search.editText.setOnEditorActionListener { textView, _, e ->
            keyword = textView.text.toString()
            viewModel.search(keyword)
            true
        }
        binding.search.addTransitionListener { searchView, previousState, newState ->
            if (newState == SearchView.TransitionState.SHOWING) {
                searchAdapter.clear()
                binding.history.isVisible = true
                binding.history.removeAllViews()
                val key = SPUtils.instance.getStringSet("keywords", setOf())
                key.forEach {
                    val chip:KeywordBinding = DataBindingUtil.inflate(layoutInflater, R.layout.keyword, binding.history, true)
                    chip.key.setText(it)
                    chip.key.setOnClickListener { _ ->
                        keyword = it
                        binding.search.editText.setText(keyword)
                        viewModel.search(keyword)
                    }
                }
            }
        }
    }

    override fun error(throwable: kotlin.Throwable) {
        super.error(throwable)
        binding.refresh.closeHeaderOrFooter()
    }
}